//
//  XDAudioViewController.m
//  testDownloadDemo
//
//  Created by XDWY on 2018/3/22.
//  Copyright © 2018年 XDWY. All rights reserved.
//

#import "XDAudioViewController.h"
#import "CDPAudioRecorder.h"

@interface XDAudioViewController ()<CDPAudioRecorderDelegate>{
    
    CDPAudioRecorder *_recorder;
}

@property(nonatomic,strong)UIImageView *audioImageView;

@property(nonatomic,strong)UIButton *recordBtn;

@property(nonatomic,strong)UIButton *playBtn;


@end

@implementation XDAudioViewController

#pragma mark - Init
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.audioImageView.frame =CGRectMake(100, 200, 100, 100);
    self.recordBtn.frame =CGRectMake(100, CGRectGetMaxY(self.audioImageView.frame) +10, 100, 40);
    self.playBtn.frame =CGRectMake(CGRectGetMaxX(self.recordBtn.frame) +20, CGRectGetMinY(self.recordBtn.frame), 100, 40);
    
    [self.view addSubview:self.audioImageView];
    [self.view addSubview:self.recordBtn];
    [self.view addSubview:self.playBtn];
    
    _recorder =[CDPAudioRecorder shareRecorder];
    _recorder.delegate =self;
    
    // Do any additional setup after loading the view.
}
-(void)dealloc {
    
    [_recorder stopPlaying];
    [_recorder stopRecording];
}

#pragma mark - Action Methods
// 开始录音
-(void)startRecordBtn:(UIButton *)btn {
    [_recorder startRecording];
}
// 结束录音
-(void)endRecordBtn:(UIButton *)btn {
    double recoderTime =_recorder.recorder.currentTime;
    if (recoderTime <1.0) { // 录音时间太短
        self.audioImageView.image = [UIImage imageNamed:@"mic_0"];
        [DisplayHelper displayWarningAlert:@"说话时间太短"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [_recorder stopRecording];
            [_recorder deleteAudioFile];
        });
    }else { // 正常录音
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [_recorder stopRecording];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.audioImageView.image=[UIImage imageNamed:@"mic_0"];
            });
        });
        
    }
}
// 取消录音
-(void)cancleRecordBtn:(UIButton *)btn {
    self.audioImageView.image = [UIImage imageNamed:@"mic_0"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [_recorder stopRecording];
        [_recorder deleteAudioFile];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [DisplayHelper displayWarningAlert:@"已取消录音了"];
        });
    });
}
// 播放录音文件
-(void)playBtnClick:(UIButton *)btn {
    [_recorder playAudioFile];
}

#pragma mark - CDPAudioRecorderDelegate

//录音结束(url为录音文件地址,isSuccess是否录音成功)
-(void)recordFinishWithUrl:(NSString *)url isSuccess:(BOOL)isSuccess{
    //url为得到的caf录音文件地址,可直接进行播放,也可进行转码为amr上传服务器
    NSLog(@"录音完成,文件地址:%@",url);
    
    return;
    
    //如果需要将得到的caf录音文件进行转码为amr格式,可按照以下步骤转码
    //生成amr文件将要保存的路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"CDPAudioFiles/CDPAudioRecord.amr"];
    
    //caf转码为amr格式
    [CDPAudioRecorder convertCAFtoAMR:[NSURL URLWithString:url].path savePath:filePath];
    
    NSLog(@"转码amr格式成功----文件地址为:%@",filePath);
}

//更新音量分贝数峰值(0~1)
-(void)updateVolumeMeters:(CGFloat)value{
    NSInteger no=0;
    
    if (value>0&&value<=0.14) {
        no = 1;
    } else if (value<= 0.28) {
        no = 2;
    } else if (value<= 0.42) {
        no = 3;
    } else if (value<= 0.56) {
        no = 4;
    } else if (value<= 0.7) {
        no = 5;
    } else if (value<= 0.84) {
        no = 6;
    } else{
        no = 7;
    }
    
    NSString *imageName = [NSString stringWithFormat:@"mic_%ld",(long)no];
    _audioImageView.image = [UIImage imageNamed:imageName];
}


#pragma mark - Setter & Getter
-(UIImageView *)audioImageView {
    if (!_audioImageView) {
        _audioImageView =[[UIImageView alloc]init];
        _audioImageView.image =[UIImage imageNamed:@"mic_0"];
    }
    return _audioImageView;
}
-(UIButton *)recordBtn {
    if (!_recordBtn) {
        _recordBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        [_recordBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
        [_recordBtn setTitle:@"松开 结束" forState:UIControlStateHighlighted];
        [_recordBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_recordBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
        
        [_recordBtn addTarget:self action:@selector(startRecordBtn:) forControlEvents:UIControlEventTouchDown];
        [_recordBtn addTarget:self action:@selector(endRecordBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_recordBtn addTarget:self action:@selector(cancleRecordBtn:) forControlEvents:UIControlEventTouchDragExit];
        _recordBtn.layer.cornerRadius =10;
        _recordBtn.backgroundColor =[UIColor blueColor];
    }
    return _recordBtn;
}
-(UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _playBtn.adjustsImageWhenHighlighted = NO;
        [_playBtn setTitle:@"播 放" forState:UIControlStateNormal];
        [_playBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        _playBtn.layer.cornerRadius = 10;
        _playBtn.backgroundColor=[UIColor yellowColor];
        [_playBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
